package cn.mesmile.emqtt.client;

import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.springframework.stereotype.Component;

/**
 * @author zb
 * @date 2021/7/11 15:51
 * @Description
 */
@Slf4j
@Component
public class MqttMessageCallBack  implements MqttCallback {

//    private final EmqClient emqClient;
//
//    public MqttMessageCallBack(EmqClient emqClient) {
//        this.emqClient = emqClient;
//    }


    @Override
    public void connectionLost(Throwable throwable) {
        // 丢失对服务端的连接后触发该方法回调，此处可以做一些特殊处理，比如重连
        log.info(">>>>>>>>>>> 丢失了对broker的连接");
        // 重连
//        emqClient.reConnect();
    }

    /**
     *  应用收到消息后触发的回调
     *  订阅到消息后的回调
     *      该方法由mqtt客户端同步调用， 在此方法未正确返回之前， 不会发送ack确认消息到broker
     *      一旦该方法向外抛出了异常 客户端将异常关闭， 当再次连接时；
     *      所有QoS 1， QoS 2且客户端未进行ack确认的消息都将由 broker服务器再次发送到客户端
     * @param topic
     * @param mqttMessage
     * @throws Exception
     */
    @Override
    public void messageArrived(String topic, MqttMessage mqttMessage) throws Exception {
        byte[] payload = mqttMessage.getPayload();
        log.info(">>>>>>>> [订阅者收到消息]：topic:{}, messageId:{}, qos:{}, msg:{}",
                    topic, mqttMessage.getId(), mqttMessage.getQos(), new String(payload)
                );
    }

    /**
     *  发布者消息发送完成触发回调
     *      Qos 0 消息 PUBLISH 后触发回调
     *      Qos 1 消息 PUBACK  手动确认后触发回调
     *      Qos 2 消息 PUBCOMP 收到确认发布完成后触发回调
     * @param iMqttDeliveryToken
     */
//    @SneakyThrows  // lombok 帮忙try catch 处理异常
    @Override
    public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {

        int messageId = iMqttDeliveryToken.getMessageId();
        String[] topics = iMqttDeliveryToken.getTopics();
        log.info(">>>>>>>> [发布者]消息[发布完成]：msgId:{}", messageId);
//
//        byte[] payload = message.getPayload();
//        int qos = message.getQos();
//        int id = message.getId();
//        log.info(">>>>>>>> [发布者]消息[发布完成]：msg:{}, topics:{}, qos:{}, id:{}", new String(payload), topics ,qos, id);
    }
}
